#include <Windows.h>
#include <string>
#include <shlobj.h>
#include "..\FilesRefactor\FilesRefactor.h"
#include "..\FilerFrogUtils\FilerFrogUtils.h" 

using namespace std;

int WINAPI WinMain(HINSTANCE hInstance,
				   HINSTANCE hPrevInstance,
				   LPSTR lpCmdLine,
				   int nCmdShow
				   )
{

	//::MessageBox(NULL, L"Attach", L"Attach", 0);

	wstring args[3];
	wstring cmdLine = GetCommandLine();

	int count = 0;
	int begin = 0;
	int end = 0;
	int total = 0;
	unsigned int i;

	for (i=0; i < cmdLine.length(); i++)
    {        
		if (cmdLine.at(i) == L'"')
        {
			count++;

			if (count == 2)
			{
				count = 0;
			}
        }
		else if (cmdLine.at(i) == L' ' && count == 0)
		{
			if (total > 2)
			{
				break;
			}

			end = i;
			args[total] = cmdLine.substr(begin, end - begin);
			total++;		
			begin = end + 1;			
		}
	}

	if (total < 3)
	{
		end = i;
		args[total] = cmdLine.substr(begin, end - begin);
	}

	STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

	args[2] =  args[2].substr(0, args[2].length() - 1);
	wchar_t cmdArgs[1024];

	if (args[1] == L"/Install")
	{
		FilesRefactor fr(NULL, NULL, NULL);
		list<wstring> path;
		wstring frogAppDataPath = FilerFrogUtils::GetFrogAppDataPath();
		path.push_back(frogAppDataPath);

		FRRESPONSE tempResult;
		fr.RenameFilesAlphabetize(tempResult, path, true);

		wstring dllPath = (wstring)L"regsvr32 /s " + args[2] + L"FilerFrog.dll\"";
		wcscpy_s(cmdArgs, 1024, dllPath.c_str());
	}
	else if (args[1] == L"/Uninstall" || args[1] == L"Rollback")
	{
		wstring dllPath = (wstring)L"regsvr32 /s /u " + args[2] + L"FilerFrog.dll\"";
		wcscpy_s(cmdArgs, 1024, dllPath.c_str());
	}

	// Start the child process. 
	CreateProcess(
		NULL,			// No module name (use command line)
		cmdArgs,        // Command line
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		0,              // No creation flags
		NULL,           // Use parent's environment block
		NULL,           // Use parent's starting directory 
		&si,            // Pointer to STARTUPINFO structure
		&pi);           // Pointer to PROCESS_INFORMATION structure

	// Notify Shell
	SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
	

	return 0;
}
